package com.wwwarehouse.contract.release_supply_requirements;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.SlideBarView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.contract.bean.SelectResourseBean;
import com.wwwarehouse.contract.common.ContractCommon;
import com.wwwarehouse.contract.core.ContractConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * @创建者 chenchao.
 * @创建时间 2017/9/22 19:04
 * @描述 ${TODO}
 */
@Route(path = "/contract/SelectResourceFragment")
public class SelectResourceFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private CustomViewPagerInternal mVpContain;
    private CirclePageIndicator mPageIndicate;
    private Button mBtSure;
    private StateLayout mStateLayout;
    private List<Fragment> mFragmentList;
    public static final int PAGE = 1;
    public static final int SIZE = 9;
    private SlideBarView mSlideBarView;
    private SelectResourceFragmentChild mSelectResourceFragmentChild;
    private Map mUnPublishMap;
    private long mBigUkid;
    private Bundle mBundleAsk;
    //    private String mUkid;
    private SelectResourseBean mSelectResourseBean;
    private List<SelectResourseBean.ListBean> mSelectToCanSeePublishList;
    private String mTaskTypeUkid;
    private ElasticScrollView mEsPublish;
    private boolean isShow;
    private Bundle mPublishNumBundle;
    private RelativeLayout mRl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_select_resourse, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (isShow) {
            ((BaseCardDeskActivity) mActivity).hideTitleBt();
        }

    }

    private void initView() {
        mRl = findView(mView, R.id.rl_bt);
        mStateLayout = findView(mView, R.id.sl);
        mVpContain = findView(mView, R.id.cvpi);
        mPageIndicate = findView(mView, R.id.cpi);
        mSlideBarView = findView(mView, R.id.sbv_slide);
        mBtSure = findView(mView, R.id.btn_sure);
        mBtSure.setOnClickListener(this);
        mEsPublish = findView(mView, R.id.es_publish);
        mEsPublish.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                if (!isShow) {
                    ((BaseCardDeskActivity) mActivity).downPull_3();
                    ((BaseCardDeskActivity) mActivity).showTitleBt1();

                } else {
                    ((BaseCardDeskActivity) mActivity).hideTitleBt();
                }
                isShow = !isShow;


            }

            @Override
            public void onUpPull() {

            }
        });
    }

    private void initData() {
        mPublishNumBundle = new Bundle();//向下个界面传的bundle
        mSelectToCanSeePublishList = new ArrayList<>();
        //在Common里面存一个集合  在adapter里面进行选择的时候向集合里面添加bean
        ContractCommon.getInstance().setSelectToCanSeePublishList(mSelectToCanSeePublishList);
        mFragmentList = new ArrayList<>();
        mUnPublishMap = new HashMap();
        Bundle bundle = getArguments();
        if (bundle != null && bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS) != null) {
            CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            mTaskTypeUkid = taskBean.getBusinessId();
//                                    mTaskTypeUkid = "20170922001";
//                    mTaskTypeUkid = "1000021";
            mBigUkid = Long.parseLong(mTaskTypeUkid);
            mUnPublishMap.put("ownerUkid", mBigUkid);
            mUnPublishMap.put("page", PAGE);
            mUnPublishMap.put("release", 0);
            mUnPublishMap.put("size", SIZE);
            getUnPublishList();
        }
//        Button titleBt1 = ((BaseCardDeskActivity) mActivity).getTitleBt1();
//        titleBt1.setText(mActivity.getResources().getString(R.string.history_publish));
//        titleBt1.setTextColor(ContextCompat.getColor(mActivity, R.color.common_color_c3_ffffff));
//        titleBt1.setBackground(mActivity.getResources().getDrawable(R.drawable.selector_pinka_right_top_btn));
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
//                (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        params.setMargins(0, ConvertUtils.dip2px(mActivity, 5), ConvertUtils.dip2px(mActivity, 15), ConvertUtils.dip2px(mActivity, 5));
//        titleBt1.setLayoutParams(params);
//        titleBt1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPublishNumBundle.putLong("buId", mBigUkid);
//                pushFragment("/contract/PublishResourceListFragment", mPublishNumBundle);
//                if (ContractCommon.getInstance().getSelectToCanSeePublishList().size() == 0) {
//                    mRl.setVisibility(View.INVISIBLE);
//                    mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
//                }
//                ((BaseCardDeskActivity) mActivity).hideTitleBt();
//            }
//        });

//        ((BaseCardDeskActivity) mActivity).showTitleBt1();
        ((BaseCardDeskActivity) mActivity).setTitleBt1Text(mActivity.getResources().getString(R.string.history_publish));
    }

    @Override
    public void titleBt1Click() {
        if (peekFragment() instanceof SelectResourceFragment) {
            mPublishNumBundle.putLong("buId", mBigUkid);
            pushFragment("/contract/PublishResourceListFragment", mPublishNumBundle);
            if (ContractCommon.getInstance().getSelectToCanSeePublishList().size() == 0) {
                mRl.setVisibility(View.INVISIBLE);
                mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
            }
            ((BaseCardDeskActivity) mActivity).hideTitleBt();
        }

    }

    private void getUnPublishList() {
        mStateLayout.showProgressView(true);//加载时候的状态
        NoHttpUtils.httpPost(ContractConstant.EUERY_UNPUBLISH_LIST, mUnPublishMap, mOnResponseListener, 0);
        //        NoHttpUtils.httpPost("router/api?method=tempPbContract.queryUnPublishList&version=1.0.0", mUnPublishMap, mOnResponseListener, 0);
    }

    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            try {
                switch (i) {
                    case 0:
                        if ("0".equals(commonClass.getCode())) {

                            mSelectResourseBean = JSON.parseObject(commonClass.getData().toString(), SelectResourseBean.class);

                            //总共多少页
                            int total = mSelectResourseBean.getTotal();
                            if (total == 0) {
                                mStateLayout.showEmptyView(true);//请求回来为空
                                mStateLayout.setEmptyListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        getUnPublishList();
                                    }
                                });
                            } else {

                                final int page = (total % 9 == 0) ? total / 9 : (total / 9 + 1);
                                mFragmentList.clear();
                                for (int j = 0; j < page; j++) {
                                    mBundleAsk = new Bundle();
                                    newFragment(j);//创建子fragment
                                    mSelectResourceFragmentChild.setArguments(mBundleAsk);
                                    mFragmentList.add(mSelectResourceFragmentChild);
                                }
                                mVpContain.setAdapter(new ContractFragmentPagerAdapter(getFragmentManager(), mFragmentList));
                                //                                if (isSeleteToHistory) {//上滑按钮点击之后回来
                                //                                    EventBus.getDefault().post("DELETE_TO_HISTORY");
                                //                                    selectNum = 0;
                                //                                    mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
                                //                                    isSeleteToHistory = false;
                                //                                }

                                if (page <= 6) {
                                    mPageIndicate.setVisibility(View.VISIBLE);
                                    mSlideBarView.setVisibility(View.GONE);
                                    mPageIndicate.setViewPager(mVpContain, 0);
                                } else {
                                    mPageIndicate.setVisibility(View.GONE);
                                    mSlideBarView.setVisibility(View.VISIBLE);
                                    mSlideBarView.setTotalPage(page);
                                    mSlideBarView.setOnSlideChange(new SlideBarView.OnSlideChange() {
                                        @Override
                                        public void onSlideChange(int i) {
                                            mVpContain.setCurrentItem(page, false);
                                        }
                                    });
                                    mSlideBarView.setViewPagerInternal(mVpContain);
                                }
                            }
                        } else {
                            mStateLayout.showSystemView(commonClass.getMsg(), true);
                            mStateLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    getUnPublishList();
                                }
                            });
                        }
                        break;
                }
            } catch (Exception e) {
                LogUtils.showLog("Exception" + e.toString());
            }


        }

        @Override
        public void onFailed(String s, int i) {
            mStateLayout.showNetworkView(true);//网络问题
            mStateLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getUnPublishList();
                }
            });
        }

        @Override
        public void onFinish(int i) {
            mStateLayout.showContentView();
        }
    };

    private boolean isBACK;

    public void onEventMainThread(String string) {
        if ("SELECTNUMADD".equals(string)) {

            mActivity.setTitle(mActivity.getResources().getString(R.string.select_res) + ContractCommon.getInstance().getSelectToCanSeePublishList().size() + ")");
            isBACK = true;
            mRl.setVisibility(View.VISIBLE);
        } else if ("SELECTNUMLESS".equals(string)) {
            if (ContractCommon.getInstance().getSelectToCanSeePublishList().size() > 0) {
                mActivity.setTitle(mActivity.getResources().getString(R.string.select_res) + ContractCommon.getInstance().getSelectToCanSeePublishList().size() + ")");
            } else {
                mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
                mRl.setVisibility(View.INVISIBLE);
            }
        } else if ("HISTORY_BACK_SELECT".equals(string)) {
//            mRl.setVisibility(View.VISIBLE);
            if (ContractCommon.getInstance().isSeleteToHistory()) {
                getUnPublishList();

            }

        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SelectResourceFragment) {
            if (!isBACK) {
                mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
            } else {
                if (ContractCommon.getInstance().getSelectToCanSeePublishList().size() == 0) {
                    mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
                } else {
                    mActivity.setTitle(mActivity.getResources().getString(R.string.select_res) + ContractCommon.getInstance().getSelectToCanSeePublishList().size() + ")");
                }

            }
        }

    }

    @Override
    public void requestDatas() {

    }

    private void newFragment(int j) {
        mSelectResourceFragmentChild = new SelectResourceFragmentChild();

        mBundleAsk.putString("ownerUkid", mTaskTypeUkid);
        mBundleAsk.putInt("page", j + 1);

    }

    @Override
    public void onClick(View v) {
        Bundle selectToCanSeePublishBundle = new Bundle();
        selectToCanSeePublishBundle.putString("buId", mTaskTypeUkid);
        pushFragment("/contract/LocalPublishResourceListFragment", selectToCanSeePublishBundle);
        mActivity.setTitle(mActivity.getResources().getString(R.string.select_re));
        mRl.setVisibility(View.INVISIBLE);
    }


}
